package com.yc.vote.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yc.vote.entity.Items;
import com.yc.vote.entity.Vote;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * <p>
 * 投票系统-题目表-2 Mapper 接口
 * </p>
 *
 * @author baomidou
 * @since 2024-04-16
 */
public interface VoteMapper extends BaseMapper<Vote> {
    @Select("select * from tp_vote where id =#{id}")
    @Results(
            id = "rm1",
            value = {
                 @Result(column = "id" , property = "id" ,id = true),
                 @Result(column = "id" , property = "items" ,
                 many = @Many(select ="selectItemsByVid")),
                    @Result(column = "id" ,property = "unum",
                    one  =@One(select = "countUnumByVid"))
            }
    )
  Vote selectById(int id);

    @Update("update tp_vote set vname = #{vname} ,vtype = #{vtype} where id =#{id}")
    int updateVote(String vname,String vtype,int id);



    @Select("select a.*, IFNULL(b.cnt,0) unum\n" +
            "from tp_items a " +
            " left join (select iid, count(*) cnt " +
            "           from tp_record " +
            "           where vid=#{vid} " +
            "           group by iid) b on a.id=b.iid " +
            " where vid=#{vid}")
    List<Items> selectItemsByVid(int vid);

    @Select("select count(Distinct usid) unum,vid\n"+
            " from tp_record\n" +
            " where vid =#{vid}\n" +
            " group by vid")
    int countUnumByVid(int vid);

    @Select("<script>" +
            "select * from tp_vote" +
            "<where>" +
            " status = 1 " +  // 查询, 排除逻辑删除的记录
            "<if test='vname!=null'>and vname like concat('%',#{vname},'%')</if>" +
            "</where>" +
            "</script>")
    @ResultMap("rm1")
    List<Vote> selectLikeVname(@Param("vname") String vname);


    //MyBatisPlus 分页查询
    @Select("<script>" +
            "select * from tp_vote" +
            "<where>" +
            " status = 1 " +  // 查询, 排除逻辑删除的记录
            "<if test='vname!=null'>and vname like concat('%',#{vname},'%')</if>" +
            "</where>" +
            "</script>")
    @ResultMap("rm1")
    IPage<Vote> selectLikeVname(@Param("vname") String vname, IPage<Vote> page);
}
